package com.purchase.ml.resource.common;

import com.purchase.ml.bean.base.ApiRestResult;
import com.purchase.ml.bean.req.file.FileUploadDto;
import com.purchase.ml.bean.req.file.ImageDto;
import com.purchase.ml.exception.BizException;
import com.purchase.ml.exception.CommonEnum;
import com.purchase.ml.utils.FileUploadAndDownUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.weaver.ast.Var;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @author :zxm
 * @date :2021/2/27 16:38
 * @description :文件上传接口
 **/
@RestController
@RequestMapping("/file")
@Slf4j
public class FileResource {
    private String randomName = randomDirName();

    @PostMapping("/uploadFile")
    @ApiOperation(value = "上传接口")
    public ApiRestResult multipartFile(FileUploadDto dto, MultipartFile[] mf){
        log.info("uploadFileuploadFileuploadFile");
        Map<String, List<String>> map = new HashMap<>();
        Map<String, List<ImageDto>> prodMap = new HashMap<>();
        switch (dto.getNum()){
            case 0:
                map = this.uploadFile(mf, "logo");
                break;
            case 1:
                map = this.uploadFile(mf,"head");
                break;
            case 2:
                String rootName = getProdRootPath("prod");
                prodMap = this.uploadProdFile(mf,rootName,dto);
                return ApiRestResult.ok(prodMap);
            default:
                throw new BizException(CommonEnum.ILLEGAL_REQ_ERROR);
        }
        return ApiRestResult.ok(map);
    }

    // 处理商品上传的图片
    private Map<String, List<ImageDto>> uploadProdFile(MultipartFile[] fileList, String rootName,FileUploadDto dto) {
        if(dto.getIndex()==null || dto.getIndex().size()==0){
            throw new BizException(CommonEnum.IMAGE_FILE_UPLOAD_INDEX_IS_NULL);
        }
        MultipartFile mf = null;
        Map<String, List<String>> src = new HashMap<>();
        // 用于存放图片路径
        List<String> list = new ArrayList<>();
        Map<String, List<ImageDto>> imageMap = new HashMap<>();
        List<ImageDto> imageList = new ArrayList<>();
        if(fileList.length > 1) {
            for (int i = 0; i < fileList.length; i++) {
                src = getDetailFileUpload(fileList[i],rootName,src,list);
                ImageDto image = new ImageDto(src.get("picUrl").get(i), dto.getIndex().get(i));
                imageList.add(image);
                imageMap.put("picUrl",imageList);
            }
        }else if(fileList.length == 1){
            src = getDetailFileUpload(fileList[0],rootName,src,list);
            ImageDto image = new ImageDto(src.get("picUrl").get(0), dto.getIndex().get(0));
            imageList.add(image);
            imageMap.put("picUrl",imageList);
        }else {
            throw new BizException(CommonEnum.IMAGE_FILE_UPLOAD_ERROR);
        }
        return imageMap;
    }
    // 处理公司logo及用户头像
    private Map<String, List<String>> uploadFile(MultipartFile[] fileList, String rootName) {
        MultipartFile mf = null;
        Map<String, List<String>> src = new HashMap<>();
        // 用于存放图片路径
        List<String> list = new ArrayList<>();
        if(fileList.length==1){
            mf = fileList[0];
            src = getDetailFileUpload(mf,rootName,src,list);
        }else {
            throw new BizException(CommonEnum.IMAGE_FILE_UPLOAD_ERROR);
        }
        return src;
    }

    // 进行上传操作
    @NotNull
    private Map<String, List<String>> getDetailFileUpload(MultipartFile mf,String rootName,Map<String,List<String>> src,List<String> list) {
        // 1.获取上传文件的名称
        String oldName = mf.getOriginalFilename();
        // 2.根据当前时间获取文件夹的名字
        String dirNameByCurrentDate = FileUploadAndDownUtil.getDirNameByCurrentDate();
        String childPathName = "/images/"+dirNameByCurrentDate+"/"+rootName;
        // 3. 如果当前目录不存在，则创建一个。
        // 存放上传图片的文件夹
        File fileDir = FileUploadAndDownUtil.getImgDirFile();
        File dirFile = new File(fileDir.getAbsolutePath(), childPathName);
        if(!dirFile.exists()){
            dirFile.mkdirs();
        }
        // 4.生成文件的新名称
        String newName = FileUploadAndDownUtil.getNewNameByUUID(oldName);
        // 5.上传文件
        File file = new File(dirFile, newName);
        try {

            mf.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 注意：上传文件到页面使用相对路径。不能使用绝对路径。
        list.add(childPathName+"/"+newName);
        src.put("picUrl",list);
        return src;
    }

    // 拼接商品图片存放路径
    private String getProdRootPath(String rootName){
        String dirNameByCurrentDate = FileUploadAndDownUtil.getDirNameByCurrentDate();
        String childPathName = "/images/"+dirNameByCurrentDate+"/"+rootName+"/"+randomName;

        File fileDir = FileUploadAndDownUtil.getImgDirFile();
        File dirFile = new File(fileDir.getAbsolutePath(), childPathName);
        if(!dirFile.exists()){
            dirFile.mkdirs();
        }
        File[] files = dirFile.listFiles();
        if (files.length>200) {
            randomName = randomDirName();
        }
        return rootName+"/"+randomName;
    }
    // 获取商品随机文件夹名
    private static String randomDirName(){
        StringBuffer str = new StringBuffer();
        Random random = new Random();
        for (int i = 0; i < 8; i++ ){
            int name = random.nextInt(9);
            str.append(name);
        }
        return str.toString();
    }
}
